package com.springboot.utils;

import com.springboot.entity.ProductSpecColor;
import com.springboot.entity.ProductSpecSize;
import com.springboot.mapper.ProductSpecColorMapper;
import com.springboot.mapper.ProductSpecSizeMapper;

/**
 * 规格值转换工具类
 *
 * @author zjb
 * @since 2025/11/08
 */
public class SpecValuesToNamesUtils {
    
    /**
     * 将规格值ID组合转换为规格值名称组合
     * 例如: "10:29" -> "红色:L"
     *
     * @param specValues 规格值ID组合（格式：colorId:sizeId）
     * @param productSpecColorMapper 颜色Mapper
     * @param productSpecSizeMapper 尺码Mapper
     * @return 规格值名称组合
     */
    public static String convertSpecValuesToNames(String specValues,
                                                  ProductSpecColorMapper productSpecColorMapper,
                                                  ProductSpecSizeMapper productSpecSizeMapper) {
        if (specValues == null || specValues.isEmpty()) {
            return specValues;
        }

        // 预期格式为 "colorId:sizeId"
        String[] valueIds = specValues.split(":");
        if (valueIds.length != 2) {
            return specValues;
        }

        StringBuilder result = new StringBuilder();

        // 颜色
        try {
            Integer colorId = Integer.parseInt(valueIds[0]);
            ProductSpecColor color = productSpecColorMapper.selectById(colorId);
            if (color != null) {
                result.append(color.getColorName());
            } else {
                result.append(valueIds[0]);
            }
        } catch (NumberFormatException e) {
            result.append(valueIds[0]);
        }

        result.append(":");

        // 尺码
        try {
            Integer sizeId = Integer.parseInt(valueIds[1]);
            ProductSpecSize size = productSpecSizeMapper.selectById(sizeId);
            if (size != null) {
                result.append(size.getSizeName());
            } else {
                result.append(valueIds[1]);
            }
        } catch (NumberFormatException e) {
            result.append(valueIds[1]);
        }

        return result.toString();
    }
}